package cli

import (
	"fmt"
	"log"
	"net"

	cli "github.com/urfave/cli/v2"
)

var EchoCmd = &cli.Command{
	Name:  "echo",
	Usage: "启动一个回显服务器",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "port",
			Usage: "监听端口 例如: 10058, default: 10058",
			Value: "10058",
		},
	},
	Action: func(cctx *cli.Context) error {
		listener, err := net.Listen("tcp", "0.0.0.0:"+cctx.String("port"))
		log.Printf("listen %s, %v\n", listener.Addr().String(), err)
		if err != nil {
			return err
		}

		for {
			conn, err := listener.Accept()
			if err != nil {
				continue
			}
			log.Printf("%s connected\n", conn.RemoteAddr().String())
			go func() {
				for {
					buf := make([]byte, 4096)
					n, err := conn.Read(buf)
					if err != nil {
						log.Printf("%s disconnect %v\n", conn.RemoteAddr().String(), err)
						return
					}
					fmt.Println(string(buf[0:n]))
					conn.Write(buf[0:n])
				}
			}()
		}
	},
}
